const app = getApp()
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatTimes = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return [year, month, day].map(formatNumber).join('-')
}
//两个时间相差多少分钟
const timeDifference = (beginTime, endTime) => {
  // beginTime, endTime
  //定义两个变量time1,time2分别保存开始和结束时间
  //判断开始时间是否大于结束日期
  if (beginTime > endTime) {
    let t = beginTime
    beginTime = endTime
    endTime = t
  }
  //截取字符串，得到日期部分"2009-12-02",用split把字符串分隔成数组
  var begin1 = beginTime.substr(0, 10).split("-");
  var end1 = endTime.substr(0, 10).split("-");
  //将拆分的数组重新组合，并实例成化新的日期对象
  var date1 = new Date(begin1[1] + - + begin1[2] + - + begin1[0]);
  var date2 = new Date(end1[1] + - + end1[2] + - + end1[0]);
  //得到两个日期之间的差值m，以分钟为单位
  //Math.abs(date2-date1)计算出以毫秒为单位的差值
  //Math.abs(date2-date1)/1000得到以秒为单位的差值
  //Math.abs(date2-date1)/1000/60得到以分钟为单位的差值
  var m = parseInt(Math.abs(date2 - date1) / 1000 / 60);
  //小时数和分钟数相加得到总的分钟数
  //beginTime.substr(11,2)截取字符串得到时间的小时数
  //parseInt(beginTime.substr(11,2))*60把小时数转化成为分钟
  var min1 = parseInt(beginTime.substr(11, 2)) * 60 + parseInt(beginTime.substr(14, 2));
  var min2 = parseInt(endTime.substr(11, 2)) * 60 + parseInt(endTime.substr(14, 2));
  //两个分钟数相减得到时间部分的差值，以分钟为单位
  var n = min2 - min1;
  //将日期和时间两个部分计算出来的差值相加，即得到两个时间相减后的分钟数 
  return m + n
}
// 计算年龄
const getAge = str => {
    var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})/);
    if (r == null) return false;

    var d = new Date(r[1], r[3] - 1, r[4]);
    var returnStr = "输入的日期格式错误！";

    if (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4]) {

      var date = new Date();
      var yearNow = date.getFullYear();
      var monthNow = date.getMonth() + 1;
      var dayNow = date.getDate();

      var largeMonths = [1, 3, 5, 7, 8, 10, 12], //大月， 用于计算天，只在年月都为零时，天数有效
        lastMonth = monthNow - 1 > 0 ? monthNow - 1 : 12, // 上一个月的月份
        isLeapYear = false, // 是否是闰年
        daysOFMonth = 0; // 当前日期的上一个月多少天

      if ((yearNow % 4 === 0 && yearNow % 100 !== 0) || yearNow % 400 === 0) { // 是否闰年， 用于计算天，只在年月都为零时，天数有效
        isLeapYear = true;
      }

      if (largeMonths.indexOf(lastMonth) > -1) {
        daysOFMonth = 31;
      } else if (lastMonth === 2) {
        if (isLeapYear) {
          daysOFMonth = 29;
        } else {
          daysOFMonth = 28;
        }
      } else {
        daysOFMonth = 30;
      }

      var Y = yearNow - parseInt(r[1]);
      var M = monthNow - parseInt(r[3]);
      var D = dayNow - parseInt(r[4]);
      if (D < 0) {
        D = D + daysOFMonth; //借一个月
        M--;
      }
      if (M < 0) { // 借一年 12个月
        Y--;
        M = M + 12; //
      }

      if (Y < 0) {
        returnStr = Y;

      } else if (Y === 0) {
        if (M === 0) {
          returnStr = 0 ;
        } else {
          returnStr = 0 ;
        }
      } else {
        if (M === 0) {
          returnStr = Y ;
        } else {
          returnStr = Y  ;
        }
      }

    }
    return returnStr;
  }
  const format = date => {
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return [year, month, day].map(formatNumber).join('-')
  }
const getBirthSlot = (date) => {
  let birthDay = new Date(date)
  let nowDate = new Date()
  let date1 = Date.parse(birthDay)
  let date2 = Date.parse(nowDate)
  let day = Math.ceil((date2 - date1) / (60 * 60 * 1000 * 24))
  let age = ''
  let year = Math.floor(day / 365)
  let y = day % 365
  let month = Math.floor(y / 30)
  let d = Math.floor(day % 365 % 30)
  age += year + '岁' + month + '月' + d + '天'
  return age
}
const getBirthOfDay = (day) => {
  // let birthDay = new Date(date)
  // let nowDate = new Date()
  // let date1 = Date.parse(birthDay)
  // let date2 = Date.parse(nowDate)
  // let day = Math.ceil((date2 - date1) / (60 * 60 * 1000 * 24))
  let age = ''
  let year = Math.floor(day / 365)
  let y = day % 365
  let month = Math.floor(y / 30)
  let d = Math.floor(day % 365 % 30)
  age += year + '岁' + month + '月' + d + '天'
  return age
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}


//表单验证
const rules = (data) => {
  for (let p in data) {
    if (data[p] != '' && data[p] != undefined && data[p] != null) {
      continue;
    } else {
      return {
        bool: false,
        name: p
      }
    }
  }
  return true
}

//表单验证手机号
const checkPhone = (phone) => {
  return /^1[0-9]{10}$/.test(phone)
}

//校验宝贝名字2-20个汉字,英文和全角点.
const checkBabyTrueName = (name) => {
  return /^([a-zA-Z\u4e00-\u9fa5·]){2,20}$/.test(name)
}

//校验宝贝昵称由由2-20个汉字、数字、英文组成.
const checkBabyName = (name) => {
  return /^([0-9a-zA-Z\u4e00-\u9fa5]){2,20}$/.test(name)
}

//校验是否是纯数字
const checkNum = (num) => {
  return /^[0-9]+.?[0-9]*$/g.test(num)
}

//保留一位小数
const checkRecord = (Record) => {
  return /^[1-9]((?=\d)\d)?(\.[\d])?$/.test(Record)
}

//邮箱是否合法
const isEmail = (s) => {
  return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s)
}
// 身份证是否合法
const idCard = (value) => {
  let re =
    /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
  return re.test(value)
}
// 身份证是否合法 1900-2099
const idCardInterval = (value) => {
  let re =
    /^(([1][1-5])|([2][1-3])|([3][1-7])|([4][1-6])|([5][0-4])|([6][1-5])|([7][1])|([8][1-2]))\d{4}(([1][9]\d{2})|([2]\d{3}))(([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|([3][0-1]))\d{3}[0-9X]$/
  return re.test(value)
}

//校验建议反馈内容为5-800个汉字、英文、数字、符号，不可是表情
const checkfeedback = (message) => {
  return /([\u4e00-\u9fa5_a-zA-Z0-9]|[·] ){5,800}$/.test(message)
}

const datedifference = (sDate1, sDate2) => { //sDate1和sDate2是2006-12-18格式  
  var dateSpan,
    tempDate,
    iDays;
  sDate1 = Date.parse(sDate1);
  sDate2 = Date.parse(sDate2);
  dateSpan = sDate2 - sDate1;
  dateSpan = Math.abs(dateSpan);
  iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
  return iDays
};

const getNowFormatDate = () => {
  var date = new Date();
  var seperator1 = "-";
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentdate = year + seperator1 + month + seperator1 + strDate;
  return currentdate;
}

const HttpRequst = (loading, url, method, data, callback) => {
  if (loading) {
    wx.showToast({
      title: '数据加载中',
      icon: 'loading'
    })
  }
  let TOKEN = wx.getStorageSync('usertoken')
  let hearder = {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  };
  if (!url.includes('xcxLoginByUnionId') || !url.includes('xcxAutoLogin')) {
    Object.assign(hearder, {
      "Authorization": TOKEN
    })
  }
  wx.request({
    url: getApp().globalData.serverUrl + url,
    method: method,
    data: data,
    header: hearder,
    success: function(res) {
      if (loading) {
        wx.hideToast()
      }
      if (res.data.code == 401) { //token失效重新登陆
        //检测用户是否授权
        wx.getSetting({
          success(es) {
            if (es.authSetting['scope.userInfo']) {
              //用户已经授权
              wx.getUserInfo({
                success: (ev) => {
                  var userInfo = JSON.parse(ev.rawData);
                  //根据openid登陆
                  wx.setStorageSync('catchUserInfo', userInfo);
                  wx.setStorageSync('catchUIEncryptedData', ev.encryptedData);
                  wx.setStorageSync('catchUIIv', ev.iv);
                }
              })
            } else {
              wx.setStorageSync('isLogin', false);
              app.globalData.isLogin = false;
              return;
            }
          }
        })
        wxLogin((res) => {
          if (res.data.code == 200) {
            wx.setStorageSync("telNum", res.data.data.account);
            wx.setStorageSync('usertoken', res.data.data.a_token)
            HttpRequst(loading, url, method, data, callback)
          } else if (res.data.code == 500) {
            wx.setStorageSync('isLogin', false);
            app.globalData.isLogin = false;
          }
        })
      } else {
        callback(res)
      }
    },
    fail(err) {
      console.log(err)
    },
  })

}
const wxLogin = (callback) => {
  wx.login({
    success: function(res) {
      let code = res.code;
      wx.setStorageSync('code', code);
      let userInfo = wx.getStorageSync('catchUserInfo');
      let nickName = userInfo.nickName;
      var gender = userInfo.gender;
      let avatarUrl = userInfo.avatarUrl;
      let uiIv = wx.getStorageSync('catchUIIv');
      let uiEncryptedData = wx.getStorageSync('catchUIEncryptedData');
      let relationId = wx.getStorageSync('relationId') || '';
      let sourceCode = wx.getStorageSync('sourceCode');
      HttpRequst(false, "/baby-cloud-system/authService/xcxLoginByUnionId", "post", {
        code,
        uiIv,
        uiEncryptedData,
        avatarUrl,
        gender,
        nickName,
        relationId,
        sourceCode
      }, (res => {
        callback(res)
      }))
    }
  })
}

const loginByMobile = (callback) => {
  wx.login({
    success(e) {
      let url = '/baby-cloud-system/authService/xcxLoginByMobile';
      let unionId = wx.getStorageSync('unionId');
      let code = e.code;
      let iv = wx.getStorageSync('cashIv');
      let userInfo = wx.getStorageSync('catchUserInfo');
      let nickName = userInfo.nickName;
      let gender = userInfo.gender;
      let avatarUrl = userInfo.avatarUrl;
      let encryptedData = wx.getStorageSync('cashEncryptedData');
      let relationId = wx.getStorageSync('relationId') || '';
      let sourceCode = wx.getStorageSync('sourceCode');
      if (iv && encryptedData && unionId) {
        HttpRequst(false, url, 'post', {
          unionId,
          iv,
          encryptedData,
          code,
          nickName,
          gender,
          avatarUrl,
          relationId,
          sourceCode
        }, callback)
      }
    },
  })
}

const getUserInfo = (loading, url, method, data, callback) => {
  wx.getUserInfo({
    success: function(res) {
      wx.setStorageSync('catchUserInfo', userInfo);
      wx.setStorageSync('catchUIEncryptedData', res.encryptedData);
      wx.setStorageSync('catchUIIv', res.iv);
      HttpRequst(loading, url, method, data, callback);
    },
    fail: function(res) {
      console.log("您还没有授权");
      wx.navigateTo({
        url: '/pages/index/index'
      })
    }
  })
}
const wxuuid = function() {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  s[8] = s[13] = s[18] = s[23] = "-";

  var uuid = s.join("");
  return uuid

}
const reduceDate = function(type, date, num) {
  var nowDate = null;
  var strDate = "";
  num = parseInt(num); // 防止传入字符串报错
  var seperator1 = "-";
  var seperator2 = ":";
  if (date == "") {
    nowDate = new Date();
  } else {
    nowDate = new Date(date);
  }

  if (type === "Y") {
    nowDate.setFullYear(nowDate.getFullYear() - num);
  }
  if (type === "M") {
    nowDate.setMonth(nowDate.getMonth() - num);
  }
  if (type === "D") {
    nowDate.setDate(nowDate.getDate() - num);
  }
  if (type === "A") {
    nowDate.setFullYear(nowDate.getFullYear() - num);
    nowDate.setMonth(nowDate.getMonth() - num);
    nowDate.setDate(nowDate.getDate() - num);
  }
  var year = nowDate.getFullYear(); // 年
  var month = nowDate.getMonth() + 1; // 月
  strDate = nowDate.getDate(); //日
  var hours = nowDate.getHours(); // 时
  var minutes = nowDate.getMinutes(); // 分
  var seconds = nowDate.getSeconds(); // 秒
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  if (seconds >= 0 && seconds <= 9) {
    seconds = "0" + seconds;
  }
  // var dateStr = year + seperator1 + month + seperator1 + strDate + " " + hours + seperator2 + minutes + seperator2 + seconds;
  var dateStr = year + seperator1 + month + seperator1 + strDate;
  return dateStr;
}

const addDate = function(type, date, num) {
  var nowDate = null;
  var strDate = "";
  num = parseInt(num); // 防止传入字符串报错
  var seperator1 = "-";
  var seperator2 = ":";
  if (date == "") {
    nowDate = new Date();
  } else {
    nowDate = new Date(date);
  }

  if (type === "Y") {
    nowDate.setFullYear(nowDate.getFullYear() + num);
  }
  if (type === "M") {
    nowDate.setMonth(nowDate.getMonth() + num);
  }
  if (type === "D") {
    nowDate.setDate(nowDate.getDate() + num);
  }
  if (type === "A") {
    nowDate.setFullYear(nowDate.getFullYear() + num);
    nowDate.setMonth(nowDate.getMonth() + num);
    nowDate.setDate(nowDate.getDate() + num);
  }
  var year = nowDate.getFullYear(); // 年
  var month = nowDate.getMonth() + 1; // 月
  strDate = nowDate.getDate(); //日
  var hours = nowDate.getHours(); // 时
  var minutes = nowDate.getMinutes(); // 分
  var seconds = nowDate.getSeconds(); // 秒
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  if (seconds >= 0 && seconds <= 9) {
    seconds = "0" + seconds;
  }
  // var dateStr = year + seperator1 + month + seperator1 + strDate + " " + hours + seperator2 + minutes + seperator2 + seconds;
  var dateStr = year + seperator1 + month + seperator1 + strDate;
  return dateStr;
}

const getUserDetail = (callback) => {
  HttpRequst(false, '/baby-cloud-system/mobileUser/getUserDetail', 'post', {}, res => {
    if (res.data.code == 200) {
      wx.setStorageSync('userInfo', res.data.data);
      wx.setStorageSync('coverImg', res.data.data.bgUrl);
      callback();
    }
  })
}



module.exports = {
  formatTime,
  formatTimes,
  format,
  rules,
  getBirthSlot,
  getBirthOfDay,
  datedifference,
  getNowFormatDate,
  checkPhone,
  formatDate,
  getAge,
  timeDifference,
  loginByMobile,
  HttpRequst: HttpRequst,
  wxLogin: wxLogin,
  formatDate,
  checkBabyName,
  checkBabyTrueName,
  idCard,
  idCardInterval,
  isEmail,
  checkRecord,
  checkNum,
  wxuuid,
  reduceDate,
  addDate,
  getUserDetail
}